import React, { useEffect } from 'react'
import { Link } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { useTranslation } from 'react-i18next'
import {
  CubeIcon,
  PlusIcon,
  ArrowDownTrayIcon,
  StarIcon,
  EyeIcon,
  ClockIcon,
  ArrowTrendingUpIcon
} from '@heroicons/react/24/outline'
import { AppDispatch } from '@/store'
import { fetchMyPlugins, selectMyPlugins, selectPluginsLoading } from '@/store/slices/pluginSlice'
import { selectUser } from '@/store/slices/authSlice'
import { Card, Button, StatusBadge, LoadingSkeleton } from '@/components/ui'
import { ErrorBoundary } from '@/components/common'

export const DeveloperDashboard: React.FC = () => {
  const { t } = useTranslation()
  const dispatch = useDispatch<AppDispatch>()
  const user = useSelector(selectUser)
  const myPlugins = useSelector(selectMyPlugins)
  const isLoading = useSelector(selectPluginsLoading)

  useEffect(() => {
    dispatch(fetchMyPlugins())
  }, [dispatch])

  // Calculate stats
  const stats = {
    totalPlugins: myPlugins.length,
    totalDownloads: myPlugins.reduce((sum, plugin) => sum + plugin.totalDownloads, 0),
    averageRating: myPlugins.length > 0
      ? myPlugins.reduce((sum, plugin) => sum + plugin.rating.average, 0) / myPlugins.length
      : 0,
    approvedPlugins: myPlugins.filter(plugin => plugin.status === 'approved').length,
    pendingPlugins: myPlugins.filter(plugin => plugin.status === 'pending').length
  }

  // Recent plugins (last 5)
  const recentPlugins = myPlugins
    .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
    .slice(0, 5)

  // Quick actions
  const quickActions = [
    {
      nameKey: 'dashboard.actions.createPlugin',
      descriptionKey: 'dashboard.actions.createPluginDescription',
      href: '/developer/plugins/new',
      icon: PlusIcon,
      color: 'bg-primary-500',
    },
    {
      nameKey: 'dashboard.actions.manageApiKeys',
      descriptionKey: 'dashboard.actions.manageApiKeysDescription',
      href: '/developer/api-keys',
      icon: EyeIcon,
      color: 'bg-blue-500',
    }
  ]

  if (isLoading) {
    return (
      <div className="space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          {Array.from({ length: 4 }).map((_, i) => (
            <Card key={i} className="p-6">
              <LoadingSkeleton lines={2} />
            </Card>
          ))}
        </div>
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <Card className="p-6">
            <LoadingSkeleton lines={5} />
          </Card>
          <Card className="p-6">
            <LoadingSkeleton lines={5} />
          </Card>
        </div>
      </div>
    )
  }

  return (
    <ErrorBoundary>
      <div className="space-y-6">
        {/* Welcome Header */}
        <div className="bg-gradient-to-r from-primary-600 to-purple-600 rounded-lg p-6 text-white">
          <h1 className="text-2xl font-bold mb-2">
            {t('auth.welcomeBack')}, {user?.displayName || user?.username}!
          </h1>
          <p className="text-primary-100">
            {t('dashboard.subtitle')}
          </p>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
          <Card className="p-6">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <CubeIcon className="h-8 w-8 text-primary-600" />
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-600">{t('dashboard.statistics.totalPlugins')}</p>
                <p className="text-2xl font-bold text-gray-900">{stats.totalPlugins}</p>
              </div>
            </div>
          </Card>

          <Card className="p-6">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <ArrowDownTrayIcon className="h-8 w-8 text-green-600" />
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-600">{t('dashboard.statistics.totalDownloads')}</p>
                <p className="text-2xl font-bold text-gray-900">
                  {stats.totalDownloads.toLocaleString()}
                </p>
              </div>
            </div>
          </Card>

          <Card className="p-6">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <StarIcon className="h-8 w-8 text-yellow-500" />
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-600">{t('dashboard.statistics.averageRating')}</p>
                <p className="text-2xl font-bold text-gray-900">
                  {stats.averageRating.toFixed(1)}
                </p>
              </div>
            </div>
          </Card>

          <Card className="p-6">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <ArrowTrendingUpIcon className="h-8 w-8 text-blue-600" />
              </div>
              <div className="ml-4">
                <p className="text-sm font-medium text-gray-600">{t('dashboard.statistics.pendingReviews')}</p>
                <p className="text-2xl font-bold text-gray-900">{stats.approvedPlugins}</p>
              </div>
            </div>
          </Card>
        </div>

        {/* Main Content Grid */}
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* Quick Actions */}
          <Card className="p-6">
            <Card.Header>
              <Card.Title>{t('dashboard.quickActions')}</Card.Title>
              <Card.Description>
                {t('dashboard.quickActionsDescription')}
              </Card.Description>
            </Card.Header>
            <Card.Content>
              <div className="space-y-4">
                {quickActions.map((action) => (
                  <Link
                    key={action.nameKey}
                    to={action.href}
                    className="flex items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
                  >
                    <div className={`flex-shrink-0 p-2 rounded-lg ${action.color}`}>
                      <action.icon className="h-6 w-6 text-white" />
                    </div>
                    <div className="ml-4">
                      <p className="text-sm font-medium text-gray-900">{t(action.nameKey)}</p>
                      <p className="text-sm text-gray-500">{t(action.descriptionKey)}</p>
                    </div>
                  </Link>
                ))}
              </div>
            </Card.Content>
          </Card>

          {/* Recent Plugins */}
          <Card className="p-6">
            <Card.Header>
              <Card.Title>{t('dashboard.recentPlugins')}</Card.Title>
              <Card.Description>
                {t('dashboard.recentPluginsDescription')}
              </Card.Description>
            </Card.Header>
            <Card.Content>
              {recentPlugins.length > 0 ? (
                <div className="space-y-4">
                  {recentPlugins.map((plugin) => (
                    <div key={plugin.id} className="flex items-center justify-between">
                      <div className="flex-1">
                        <Link
                          to={`/developer/plugins/${plugin.id}`}
                          className="text-sm font-medium text-gray-900 hover:text-primary-600"
                        >
                          {plugin.displayName}
                        </Link>
                        <div className="flex items-center mt-1 space-x-2">
                          <StatusBadge status={plugin.status || 'pending'} />
                          <span className="text-xs text-gray-500">
                            {new Date(plugin.updatedAt).toLocaleDateString()}
                          </span>
                        </div>
                      </div>
                      <div className="text-right">
                        <p className="text-sm text-gray-900">{plugin.totalDownloads} {t('dashboard.downloads')}</p>
                        <div className="flex items-center mt-1">
                          <StarIcon className="h-4 w-4 text-yellow-400" />
                          <span className="text-xs text-gray-500 ml-1">
                            {plugin.rating.average.toFixed(1)}
                          </span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8">
                  <CubeIcon className="mx-auto h-12 w-12 text-gray-400" />
                  <h3 className="mt-2 text-sm font-medium text-gray-900">{t('plugins.noPlugins')}</h3>
                  <p className="mt-1 text-sm text-gray-500">
                    {t('plugins.noPluginsDescription')}
                  </p>
                  <div className="mt-6">
                    <Button as={Link} to="/developer/plugins/new">
                      <PlusIcon className="h-4 w-4 mr-2" />
                      {t('plugins.createNew')}
                    </Button>
                  </div>
                </div>
              )}
            </Card.Content>
          </Card>
        </div>

        {/* Pending Reviews Alert */}
        {stats.pendingPlugins > 0 && (
          <Card className="p-6 border-yellow-200 bg-yellow-50">
            <div className="flex items-center">
              <ClockIcon className="h-6 w-6 text-yellow-600" />
              <div className="ml-3">
                <h3 className="text-sm font-medium text-yellow-800">
                  {t('dashboard.pendingReviews')}
                </h3>
                <p className="text-sm text-yellow-700">
                  {t('dashboard.pendingReviewsMessage', { count: stats.pendingPlugins })}
                </p>
              </div>
            </div>
          </Card>
        )}
      </div>
    </ErrorBoundary>
  )
}
